package com.lsmw.common_service.exceptionhandler;
/*
 *ClassName:GlobalExceptionHandler
 *UserName:二号男嘉宾
 *CreateTime:2020/11/27 17:53
 */


import com.lsmw.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //全局异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody  //为了返回数据
    public R error(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return R.internalServerError().message("执行了全局异常处理");
    }

    //特定异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody  //为了返回数据
    public R error(ArithmeticException e) {
        e.printStackTrace();
        return R.internalServerError().message("执行了算数异常处理");
    }

    //特定异常处理
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody  //为了返回数据
    public R error(HttpMessageNotReadableException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return R.internalServerError().message("执行了HttpMessageNotReadableException异常处理");
    }

    //自定义异常
    @ExceptionHandler(XXException.class)
    @ResponseBody
    public R error(XXException e){
        log.error(e.getMsg());
        e.printStackTrace();
        return R.internalServerError().code(e.getCode()).message(e.getMsg());
    }

    //自定义异常
    @ExceptionHandler(IdIllegalException.class)
    @ResponseBody
    public R error(IdIllegalException e){
        log.error(e.getMsg());
        return R.internalServerError().code(e.getCode()).message(e.getMsg());
    }

}
